package com.dmj.sqldsl.platform;

import java.util.Objects;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.testcontainers.containers.JdbcDatabaseContainer;

@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DatabaseContainer {

  private JdbcDatabaseContainer<?> realContainer;

  @Getter
  private String driverClassName;
  private String url;
  private String user;
  private String password;
  @Getter
  private H2Mode mode;

  private boolean alreadyStarted;

  public static DatabaseContainer of(JdbcDatabaseContainer<?> jdbcDatabaseContainer, H2Mode mode) {
    return DatabaseContainer.builder()
        .realContainer(jdbcDatabaseContainer)
        .driverClassName(jdbcDatabaseContainer.getDriverClassName())
        .mode(mode)
        .build();
  }

  public static DatabaseContainer h2(H2Mode mode) {
    return DatabaseContainer.builder()
        .driverClassName("org.h2.Driver")
        .url("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")
        .user("sa")
        .password("")
        .mode(mode)
        .build();
  }

  public String getUrl() {
    if (Objects.nonNull(realContainer)) {
      this.url = realContainer.getJdbcUrl();
      return this.url + mode.getDialect();
    }
    return this.url + mode.getDialect();
  }

  public String getUser() {
    if (Objects.nonNull(realContainer)) {
      this.user = realContainer.getUsername();
      return this.user;
    }
    return this.user;
  }

  public String getPassword() {
    if (Objects.nonNull(realContainer)) {
      this.password = realContainer.getPassword();
      return this.password;
    }
    return this.password;
  }

  public String getDisplayName() {
    return mode.toString();
  }

  public void start() {
    if (Objects.nonNull(realContainer) && !alreadyStarted) {
      alreadyStarted = true;
      realContainer.start();
    }
  }
}
